package com.shark.lib.rebirth;

import android.app.Activity;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Process;
import android.provider.Settings;
import android.util.Log;

import androidx.core.app.NotificationManagerCompat;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: guojr
 * @date: 2020/5/7
 */
public class IntentWrapper {
    public static final int FLAG_AUTO_START = 1;
    public static final int FLAG_BATTERY = 2;

    private static List<Intent> AUTO_START_INTENTS = new ArrayList<>();
    private static List<Intent> BATTERY_INTENTS = new ArrayList<>();

    static {
        //小米
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")));

        // 华为
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.huawei.systemmanager/.startupmgr.ui.StartupNormalAppListActivity")));
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.huawei.systemmanager/.appcontrol.activity.StartupAppControlActivity")));

        // 魅族
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.meizu.safe/.SecurityCenterActivity")));

        // 三星
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm_cn",
                "com.samsung.android.sm.autorun.ui.AutoRunActivity")));
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm_cn",
                "com.samsung.android.sm.ui.ram.AutoRunActivity")));
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm_cn",
                "com.samsung.android.sm.ui.appmanagement.AppManagementActivity")));
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm",
                "com.samsung.android.sm.autorun.ui.AutoRunActivity")));
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm",
                "com.samsung.android.sm.ui.ram.AutoRunActivity")));
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm",
                "com.samsung.android.sm.ui.appmanagement.AppManagementActivity")));
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm_cn",
                "com.samsung.android.sm.ui.cstyleboard.SmartManagerDashBoardActivity")));
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm",
                "com.samsung.android.sm.ui.cstyleboard.SmartManagerDashBoardActivity")));
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString(
                "com.samsung.android.sm_cn/.app.dashboard.SmartManagerDashBoardActivity")));
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString(
                "com.samsung.android.sm/.app.dashboard.SmartManagerDashBoardActivity")));

        // oppo
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.coloros.safecenter/.startupapp.StartupAppListActivity")));
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.coloros.safecenter/.permission.startupapp.StartupAppListActivity")));
        AUTO_START_INTENTS.add(newIntent(new ComponentName("com.coloros.safecenter", "com.coloros.privacypermissionsentry.PermissionTopActivity")));
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.oppo.safe/.permission.startup.StartupAppListActivity")));

        // vivo
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.vivo.permissionmanager/.activity.BgStartUpManagerActivity")));
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.iqoo.secure/.phoneoptimize.BgStartUpManager")));
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.vivo.permissionmanager/.activity.PurviewTabActivity")));
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.iqoo.secure/.ui.phoneoptimize.SoftwareManagerActivity")));

        // 一加
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.oneplus.security/.chainlaunch.view.ChainLaunchAppListActivity")));

        // 乐视
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.letv.android.letvsafe/.AutobootManageActivity")));

        // HTC
        AUTO_START_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.htc.pitroad/.landingpage.activity.LandingPageActivity")));



        //小米
        BATTERY_INTENTS.add(newIntent(ComponentName
                .unflattenFromString("com.miui.powerkeeper/.ui.HiddenAppsContainerManagementActivity")));

        // 华为
        BATTERY_INTENTS.add(newIntent(ComponentName
                .unflattenFromString("com.huawei.systemmanager/.power.ui.HwPowerManagerActivity")));

        // 魅族
        BATTERY_INTENTS.add(newIntent(ComponentName
                .unflattenFromString("com.meizu.safe/.SecurityCenterActivity")));

        // 三星
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm_cn",
                "com.samsung.android.sm.ui.battery.AppSleepListActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm_cn",
                "com.samsung.android.sm.ui.battery.BatteryActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm",
                "com.samsung.android.sm.ui.battery.AppSleepListActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm",
                "com.samsung.android.sm.ui.battery.BatteryActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.samsung.android.lool",
                "com.samsung.android.sm.battery.ui.BatteryActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.samsung.android.lool",
                "com.samsung.android.sm.ui.battery.BatteryActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm",
                "com.samsung.android.sm.ui.battery.BatteryActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.samsung.android.sm_cn",
                "com.samsung.android.sm.ui.cstyleboard.SmartManagerDashBoardActivity")));

        // oppo
        BATTERY_INTENTS.add(newIntent(ComponentName
                .unflattenFromString("com.coloros.safecenter/.appfrozen.activity.AppFrozenSettingsActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.coloros.oppoguardelf",
                "com.coloros.powermanager.fuelgaue.PowerUsageModelActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.coloros.oppoguardelf",
                "com.coloros.powermanager.fuelgaue.PowerSaverModeActivity")));
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.coloros.oppoguardelf",
                "com.coloros.powermanager.fuelgaue.PowerConsumptionActivity")));
        BATTERY_INTENTS.add(newIntent(ComponentName
                .unflattenFromString("com.oppo.safe/.SecureSafeMainActivity")));
        // vivo
        BATTERY_INTENTS.add(newIntent(new ComponentName("com.vivo.abe",
                "com.vivo.applicationbehaviorengine.ui.ExcessivePowerManagerActivity")));
        BATTERY_INTENTS.add(newIntent(ComponentName.unflattenFromString("com.iqoo.powersaving/.PowerSavingManagerActivity")));
    
    
    }
    
    private static Intent newIntent(ComponentName name){
        return new Intent().setComponent(name);
    }

    private static void startActivitySafely(Context context, Intent intent, int rcPermission){
        if (context == null || intent == null || rcPermission == 0){
            throw new IllegalArgumentException("StartActivity Illegal Argument");
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (context instanceof Activity) {
            ((Activity) context).startActivityForResult(intent, rcPermission);
        } else {
            context.startActivity(intent);
        }
    }

    public static final int RC_PERMISSION_AUTO_STATR_BATTERY= 2000;
    public static boolean toStartIntent(Context context, int flag){
        List<Intent> intents = null;
        if (flag != FLAG_AUTO_START && flag != FLAG_BATTERY){
            return false;
        }
        if (flag == FLAG_AUTO_START){
            intents = AUTO_START_INTENTS;
        }else if (flag == FLAG_BATTERY){
            intents = BATTERY_INTENTS;
        }
        for (Intent intent: intents){
            if (context.getPackageManager().resolveActivity(
                    intent, PackageManager.MATCH_DEFAULT_ONLY)!= null){
                try {
                    startActivitySafely(context, intent,RC_PERMISSION_AUTO_STATR_BATTERY);
                    return true;
                } catch (Exception e) {
                    continue;
                }
            }
        }
        return false;
    }


    //---------- 下列新增悬浮窗权限 ----------//

    public static final int RC_PERMISSION_OVERLAYS = 2001;

    private static final int OP_SYSTEM_ALERT_WINDOW = 24;
    public static boolean checkOverlaysPermission(Context context) {
        //android 6.0及以上的判断条件
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.canDrawOverlays(context);
        }
        //android 4.4~6.0的判断条件
        return checkCanDrawOverlays(context, OP_SYSTEM_ALERT_WINDOW);
    }

    private static boolean checkCanDrawOverlays(Context context, int op) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            Class clazz = AppOpsManager.class;
            try {
                Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
                return AppOpsManager.MODE_ALLOWED == (int) method.invoke(manager, op, Process.myUid(), context.getPackageName());
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 请求悬浮窗权限
     *
     * @param context
     */
    public static void requestDrawOverlays(Context context) {
        Intent intent = new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION", Uri.parse("package:" + context.getPackageName()));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            startActivitySafely(context, intent,RC_PERMISSION_AUTO_STATR_BATTERY);
        } else {
            Log.e("IntentWrapper", "requestDrawOverlays: No activity to handle intent");
        }
    }

    //---------- 下列新增通知权限 ----------//

    public static final int RC_PERMISSION_NOTIFY = 2002;

    public static boolean checkNotifyPermission(Context context) {
        NotificationManagerCompat manager = NotificationManagerCompat.from(context);
        // areNotificationsEnabled方法的有效性官方只最低支持到API 19，低于19的仍可调用此方法不过只会返回true，即默认为用户已经开启了通知。
        return manager.areNotificationsEnabled();
    }

    public static void requestNotifyPermission(Context context) {
        try {
            // 根据isOpened结果，判断是否需要提醒用户跳转AppInfo页面，去打开App通知权限
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);

            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
            intent.putExtra(Settings.EXTRA_CHANNEL_ID, context.getApplicationInfo().uid);

            //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);

            startActivitySafely(context, intent,RC_PERMISSION_NOTIFY);
        } catch (Exception e) {
            e.printStackTrace();
            // 出现异常则跳转到应用设置界面：锤子坚果3——OC105 API25
            Intent intent = new Intent();
            //下面这种方案是直接跳转到当前应用的设置界面。
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
            intent.setData(uri);

            startActivitySafely(context, intent,RC_PERMISSION_NOTIFY);
        }
    }

}
